<template>
  <div>
    <div class="inputStr">
      <el-button @click="showAddGoods" style="margin: 10px" type="primary">添加</el-button>
      <el-select clearable style="width: 150px;margin-right: 30px;" v-model="pagination.categoryId" placeholder="请选择分类">
        <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-input v-model="pagination.queryContent" clearable style="width: 150px" placeholder="请输入标题"></el-input>
      <el-button type="primary" icon="el-icon-search" style="margin: 15px" @click="queryStr">搜索</el-button>
    </div>
    <div v-loading="loading">
      <el-table
          :data="goodList"
          style="width: 100%">
        <el-table-column
            prop="updateTime"
            label="上次修改日期"
            align="center"
        >
        </el-table-column>
        <el-table-column
            label="图片"
            align="center"
            width="100px"
        >
          <template slot-scope="scope">
            <el-image
                :key="scope.row.images"
                style="width: 50px; height: 50px"
                lazy
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="title"
            label="标题"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="price"
            label="价格"
            align="center"
        >
        </el-table-column>
        <el-table-column
            label="状态"
            align="center"
        >
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.enable"
                @change="updateEnable(scope.row.id)"
                active-text=""
                inactive-text="">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            align="center"
            label="操作">
          <template slot-scope="scope">
            <el-button @click="showUpdate(scope.row)" type="primary" icon="el-icon-edit" circle></el-button>
            <el-button type="danger" @click="deleteById(scope.row.id)" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding-top: 40px">
      <el-pagination
          class="pagiantion"
          :total="total"
          @current-change="handleSelectionChange"
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          layout="total, prev, pager, next, jumper"
      >
      </el-pagination>
    </div>
    <el-dialog
        title="添加商品"
        :visible.sync="centerDialogVisible"
        :before-close="before2"
        width="40%"
        center>
      <div style="text-align: center">
        <span style="font-weight: bold">标题:</span>
        <el-input
            style="width: 200px"
            placeholder="请输入标题"
            v-model="good.title"
            clearable>
        </el-input>
      </div>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">分类:</span>
        <el-select clearable style="width: 200px;" v-model="good.categoryId" placeholder="请选择分类">
          <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id">
          </el-option>
        </el-select>
      </div>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">价格:</span>
        <el-input
            style="width: 200px;"
            placeholder="请输入价格"
            v-model="good.price"
            clearable>
        </el-input>
      </div>

      <el-upload
          ref="upload"
          style="text-align: center;margin-top: 10px"
          drag
          :auto-upload="false"
          list-type="picture"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :limit="1"
          :action="this.api_host+'/goods/upload'"
          multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
      </el-upload>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">状态:</span>
        <el-switch
            style="margin-left: 15px"
            v-model="good.enable"
            active-text=""
            inactive-text="">
        </el-switch>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitUpload">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
        title="编辑商品"
        :before-close="before"
        :visible.sync="centerDialogVisible2"
        width="40%"
        center>
      <div style="text-align: center">
        <span style="font-weight: bold">标题:</span>
        <el-input
            style="width: 200px"
            placeholder="请输入标题"
            v-model="good.title"
            clearable>
        </el-input>
      </div>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">分类:</span>
        <el-select clearable style="width: 200px;" v-model="good.categoryId" placeholder="请选择分类">
          <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id">
          </el-option>
        </el-select>
      </div>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">价格:</span>
        <el-input
            style="width: 200px;"
            placeholder="请输入价格"
            v-model="good.price"
            clearable>
        </el-input>
      </div>

      <el-upload
          class="avatar-uploader"
          ref="upload2"
          :file-list="fileList"
          :on-change="change"
          style="text-align: center;margin-top: 10px"
          :auto-upload="false"
          list-type="picture"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess2"
          :limit="1"
          :action="this.api_host+'/goods/upload2/'+this.good.id"
          multiple>
        <img width="150px" height="150px" v-if="good.images" :src="good.images">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <div style="text-align: center;margin-top: 10px">
        <span style="font-weight: bold">状态:</span>
        <el-switch
            style="margin-left: 15px"
            v-model="good.enable"
            active-text=""
            inactive-text="">
        </el-switch>
      </div>


      <span slot="footer" class="dialog-footer">
    <el-button @click="closeUpdate">取 消</el-button>
    <el-button type="primary" @click="updateGoods">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "GoodList",
  data() {
    return {
      loading: false,
      categoryList: [],
      centerDialogVisible: false,
      centerDialogVisible2: false,
      goodList: [],
      fileList: [],
      total: 0,
      good: {
        enable: false,
      },
      api_host: null,
      pagination: {
        currentPage: 1,
        pageSize: 5,
        queryContent: "",
        categoryId: null
      },
    }
  },
  mounted() {
    this.findCategory();
    this.findPage();
    this.api_host = this.$global_msg.api_host;
  },
  methods: {
    closeUpdate() {
      this.centerDialogVisible2 = false;
      this.findPage();
    },
    change(file, fileList) {
      this.fileList = fileList;
    },
    showAddGoods() {
      this.good = {};
      this.centerDialogVisible = true;
    },
    updateGoods() {
      if (this.good.title == null) {
        this.$message.error("请输入标题")
        return;
      }
      if (this.good.categoryId == null || this.good.categoryId == '') {
        this.$message.error("请选择分类")
        return;
      }
      if (this.good.price == null || this.good.price == '') {
        this.$message.error("请输入价格")
        return;
      }
      this.$refs.upload2.submit();
      if (this.fileList.length == 0) {
        //未修改图片
        this.axios.post("/goods/updateGoods", this.good).then(resp => {
          if (resp.data.statusCode == 200) {
            this.centerDialogVisible2 = false;
            this.$message({
              message: resp.data.message,
              type: 'success'
            });
          }
          this.good = {};
          this.findPage();
        })
      }
    },
    showUpdate(goods) {
      this.fileList = [];
      this.centerDialogVisible2 = true;
      this.good = goods;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },

    before(done) {
      this.$refs.upload2.clearFiles();
      //this.$refs.upload.clearFiles();
      done();
    },

    before2(done) {
      this.$refs.upload.clearFiles();
      //this.$refs.upload.clearFiles();
      done();
    },

    submitUpload() {
      if (this.good.title == null) {
        this.$message.error("请输入标题")
        return;
      }

      if (this.good.categoryId == null || this.good.categoryId == '') {
        this.$message.error("请选择分类")
        return;
      }

      if (this.good.price == null || this.good.price == '') {
        this.$message.error("请输入价格")
        return;
      }
      this.$refs.upload.submit();
    },

    handleAvatarSuccess(res, file) {
      this.$refs.upload.clearFiles();
      // this.good.images = URL.createObjectURL(file.raw);
      if (res.statusCode == 200) {
        this.good.images = res.data;
        this.axios.post("/goods/save", this.good).then(resp => {
          if (resp.data.statusCode == 200) {
            this.$message({
              message: resp.data.message,
              type: 'success'
            });
          }
          this.good = {};
          this.centerDialogVisible = false;
          this.findPage();
        })
      }
    },

    handleAvatarSuccess2(res, file, fileList) {
      this.$refs.upload2.clearFiles();
      // this.good.images = URL.createObjectURL(file.raw);
      if (res.statusCode == 200) {
        this.good.images = res.data;
        this.axios.post("/goods/updateGoods", this.good).then(resp => {
          if (resp.data.statusCode == 200) {
            this.$message({
              message: resp.data.message,
              type: 'success'
            });
          }
          this.good = {};
          this.centerDialogVisible2 = false;
          //this.fileList=[];
          this.findPage();
        })
      }
    },

    findCategory() {
      this.axios.get("/category/findAll").then(resp => {
        if (resp.data.statusCode == 200) {
          this.categoryList = resp.data.data;
        }
      })
    },
    updateEnable(id) {
      this.axios.put("/goods/updateEnable/" + id).then(resp => {
        if (resp.data.statusCode == 200) {
          this.$message({
            message: resp.data.message,
            type: 'success'
          });
          this.findPage();
        }
      })
    },
    deleteById(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete("/goods/deleteById/" + id).then(resp => {
          if (resp.data.statusCode == 200) {
            this.$message({
              type: 'success',
              message: resp.data.message
            });
            this.findPage();
          }
        })

      })
    },
    findPage() {
      this.loading = true;
      this.axios.post("/goods/findPage", this.pagination).then(resp => {
        if (resp.data.statusCode == 200) {
          this.total = resp.data.data.total;
          //this.pagination.toal = resp.data.data.total;
          this.goodList = resp.data.data.data;
        }
        this.loading = false;
      })
    },
    handleSelectionChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.findPage();
    },
    queryStr() {
      this.findPage();
    },
  }
}
</script>

<style scoped>
.inputStr {
  width: 550px;
  margin-left: 500px;
}
</style>
